#!/usr/bin/env python 
# -*- coding: utf-8 -*-  

import os
from PIL import Image, ImageDraw, ImageOps
from cleaner import Cleaner
from vectorizator import Vectorizator
from static import binarize

ipath = 'C:\\__eclipse__\\vector\\in_images' # входной путь
opath = 'C:\\__eclipse__\\vector\\out_images' # выходной путь

#Общий алгоритм
images = os.listdir(ipath)
for image_name in images:
    print 'open file: ' + os.path.join(ipath, image_name)
    im = Image.open(os.path.join(ipath, image_name))
    #определение размеров в миллиметрах
    w, h = im.size
    print im.format, im.size, im.mode
    im2 = im.copy()
    if im2.mode != 'L':
        im2 = im2.convert('L')
    im2 = ImageOps.invert(im2)
    
    #Бинаризация
    im = binarize(im2)
    out_name = os.path.join(opath, os.path.splitext(image_name)[0] + ".png")
    out_bin_name = os.path.join(opath, os.path.splitext(image_name)[0] + ".bin.png") 
    out_vect_name = os.path.join(opath, os.path.splitext(image_name)[0] + ".vect.png") 
    im.save(out_name)
    im.save(out_bin_name)
    
    #Очистка от соли и перца и скелетизация
    cleaner = Cleaner()
    skeleton_arr = cleaner.thin_image(im)
    skeleton_image = Image.new("RGB", (w, h), "White")
    draw = ImageDraw.Draw(skeleton_image)
    for j in xrange(1,h):
        for i in xrange(1,w):
            if skeleton_arr[i][j] != 0:
                draw.point((i,j), fill=(0,0,0))
    skeleton_image.save(out_name)
    
    #Векторизация
    vectorizaror = Vectorizator(skeleton_arr, float(w*25.4/300), float(h*25.4/300))
    result_arr, d = vectorizaror.vectorize()
    d.saveas(os.path.join(opath, os.path.splitext(image_name)[0] + ".dxf"))
    skeleton_image = Image.new("RGB", (w, h), "White")
    draw = ImageDraw.Draw(skeleton_image)
    for j in xrange(1,h):
        for i in xrange(1,w):
            if skeleton_arr[i][j] == 2:
                draw.point((i,j), fill=(204,204,0))
            if skeleton_arr[i][j] == 3:
                draw.point((i,j), fill=(0,255,0))
            if skeleton_arr[i][j] == 4:
                draw.point((i,j), fill=(255,0,0))
            if skeleton_arr[i][j] == 5:
                draw.point((i,j), fill=(250,250,250))
            if skeleton_arr[i][j] == 6:
                draw.point((i,j), fill=(250,250,250))
            if skeleton_arr[i][j] == 7:
                draw.point((i,j), fill=(0,0,255))
    skeleton_image.save(out_vect_name)
exit()